using System;
using System.Collections.Generic;
using System.Text;
using cuberga.Utils;
using cuberga.Workflow;

namespace cuberga.GA.Permutation
{
    class OXCrossover: ICoreProcess
    {
        private PermutationPopulation _parents;

        public void Perform()
        {
            // ToDo - Convert algo to code

            _parents = (PermutationPopulation)BlackBoard.Instance.Read("Parents"); // by reference
            
            // -- If rnd.getNumber < _crossoverProbability
            PermutationPopulation childs = GetChilds();//ICrossover.GetChilds(parents);
            // -- else
            // Population childs  = parents.Clone;
            // -- endif
            
            BlackBoard.Instance.Write("Childs", childs);
        }

        private PermutationPopulation GetChilds()
        {
            int cutPoint1;
            int cutPoint2;
            int leftCutPoint;
            int rightCutPoint;

            cutPoint1 = GetRandomCutPoint();
            cutPoint2 = GetRandomCutPoint();

            leftCutPoint = Math.Min(cutPoint1, cutPoint2);
            rightCutPoint = Math.Max(cutPoint1, cutPoint2);
            
            HalfOX leftOX = new HalfOX(_parents[0],
                                       _parents[1], 
                                       leftCutPoint, rightCutPoint);
            HalfOX rightOX = new HalfOX(_parents[1],
                                        _parents[0], 
                                        leftCutPoint, rightCutPoint);

            PermutationGenotype offspring1 = leftOX.GetOffspring();
            PermutationGenotype offspring2 = rightOX.GetOffspring();

            PermutationPopulation offsprings = new PermutationPopulation();
            offsprings.Add(offspring1);
            offsprings.Add(offspring2);

            return offsprings;
        
        }
        private int GetRandomCutPoint()
        {
            int length = ((int[])_parents[0].ToStructure()).Length;
            return Rand.Instance.Next(length + 1);
        }
    }
}
